//
//  XLTabBarController.m
//  XiangLove
//
//  Created by 陈宪栋 on 2018/1/9.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLTabBarController.h"
#import "XLNavgationViewController.h"
#import <UIImage+Color.h>
#import "XLMineViewController.h"
#import "ConversationListViewController.h"
#import <ReactiveCocoa.h>
#import "IMAPlatformxl.h"
#import "XLOldMainTapViewController.h"
#import "XLNewHomeViewController.h"
#import "XLAccountManager.h"
#import "XLUserInfoModel.h"
#import <UIViewController+TopViewController.h>
#import "XLTwoWayMatchingViewController.h"
#import "XLFoundViewController.h"
#import "XLImageViewController.h"


@interface UITabBar (Badge)

@end

@implementation UITabBar (Badge)
- (void)showBadgeOnItemIndex:(int)index{
    //移除之前的小红点
    [self removeBadgeOnItemIndex:index];
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]){
        //新建小红点
        UIView *badgeView = [[UIView alloc] init];
        badgeView.tag = 888 + index;
        badgeView.layer.cornerRadius = 4;
        badgeView.backgroundColor = HEXCOLOR(0xffbb01);
        CGRect tabFrame = self.frame;
        
        //    确定小红点的位置
        
//        NSInteger integer = 5;
//        if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {//是主播
//            integer = 4;
//        }
        
        NSInteger integer = 4;
        float percentX = (index + 0.6) / integer;
        CGFloat x = ceilf(percentX * tabFrame.size.width);
        CGFloat y = ceilf(0.1 * tabFrame.size.height);
        badgeView.frame = CGRectMake(x, y, 8, 8);
        [self addSubview:badgeView];
    }
}

- (void)hideBadgeOnItemIndex:(int)index{
    //移除小红点
    [self removeBadgeOnItemIndex:index];
}

- (void)removeBadgeOnItemIndex:(int)index{
    //按照tag值进行移除
    for (UIView *subView in self.subviews) {
        if (subView.tag == 888+index) {
            [subView removeFromSuperview];
        }
    }
}

@end

@interface XLTabBarController ()<UITabBarControllerDelegate>
@property (nonatomic, weak) RACDisposable *disposable;


@property (nonatomic, strong) UIImageView *  guidanceView;

@end

@implementation XLTabBarController
#pragma mark - 直播
- (void)setupLaunchMask{
    _launchMask.userInteractionEnabled = YES;
    _launchMask = [[UIView alloc] initWithFrame:CGRectMake(ScreenWidth/2-31, -25, 62, 62)];
    [self.tabBar addSubview:_launchMask];
    UIImageView *imageview1 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 62, 62)];
    imageview1.image = [UIImage imageNamed:@"tab_icon_live_back"];
    [_launchMask addSubview:imageview1];
    _launchAnimation = [LOTAnimationView animationNamed:@"zhibo"];
    _launchAnimation.cacheEnable = NO;
    _launchAnimation.frame = CGRectMake(2, 2, 58, 58);
    _launchAnimation.contentMode = UIViewContentModeScaleToFill;
    _launchAnimation.animationSpeed = 1;
    [_launchAnimation play];
    [_launchMask addSubview:_launchAnimation];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = imageview1.frame;
    [button addTarget:self action:@selector(liveBarSelect) forControlEvents:UIControlEventTouchUpInside];
    [_launchMask addSubview:button];
}
- (void)liveBarSelect{
    self.selectedIndex = 2;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.delegate = self;
    
    [self.tabBar setBackgroundImage:[UIImage imageWithSolidColor:kWhiteColor size:CGSizeMake(ScreenWidth, 49)]];
    [self.tabBar setShadowImage:[UIImage imageWithSolidColor:RGBA(46, 45, 57, 0.2) size:CGSizeMake(ScreenWidth, 1.0 / [UIScreen mainScreen].scale)]];
// QDXStart!
    [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:XiangLove_IsSH];
// QDXEnd!
    NSArray *titleNames = @[@"首页", @"求伴",@"消息", @"我的"];
    NSArray *normalImage = @[@"tab_icon_shouye_n",@"tab_icon_qiuban_n",@"tab_icon_xiaoxi_n", @"tab_icon_wode_n"];
    NSArray *selectImage = @[@"tab_icon_shouye_s",@"tab_icon_qiuban_s",@"tab_icon_xiaoxi_s", @"tab_icon_wode_s"];
    NSArray *modelClasses = @[
                              [XLFoundViewController class],
                              [XLTwoWayMatchingViewController class],
                              [ConversationListViewController class],
                              [XLMineViewController class]
                              ];
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {//是主播
        titleNames = @[@"首页", @"求伴",@"消息", @"我的"];
        normalImage = @[@"tab_icon_shouye_n",@"tab_icon_qiuban_n",@"tab_icon_xiaoxi_n", @"tab_icon_wode_n"];
        selectImage = @[@"tab_icon_shouye_s",@"tab_icon_qiuban_s",@"tab_icon_xiaoxi_s", @"tab_icon_wode_s"];
        modelClasses = @[
                         [XLFoundViewController class],
                         [XLTwoWayMatchingViewController class],
                         [ConversationListViewController class],
                         [XLMineViewController class]
                         ];
    }
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]){
        titleNames = @[@"首页",
                       @"消息",
                       @"我的"];

        normalImage = @[@"tab_icon_shouye_n",
                        @"tab_icon_xiaoxi_n",
                        @"tab_icon_wode_n"];

        selectImage = @[@"tab_icon_shouye_s",
                        @"tab_icon_xiaoxi_s",
                        @"tab_icon_wode_s"];
        modelClasses = @[
                         [XLFoundViewController class],
                         [ConversationListViewController class],
                         [XLMineViewController class]
                         ];
    }

    NSMutableArray *controllers = [[NSMutableArray alloc]init];
    for (NSInteger i = 0; i < modelClasses.count; i ++) {
        XLNavgationViewController *navController = [self creatViewControllerWithTitle:titleNames[i] controllerClass:modelClasses[i] normalImageName:normalImage[i] selectImageName:selectImage[i]];
        [controllers addObject:navController];
    }
    self.viewControllers = [controllers copy];
    
    self.selectedIndex = 0;
    @weakify(self);
    [RACObserve([IMAPlatformxl sharedInstance].conversationMgr, unReadMessageCount) subscribeNext:^(id x) {
        @strongify(self);
        if ([x integerValue] > 0) {
//            if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {//是主播
//                [self.tabBar showBadgeOnItemIndex:2];
//            }else{
//                [self.tabBar showBadgeOnItemIndex:3];
//            }
            [self.tabBar showBadgeOnItemIndex:2];
        }else {
//            if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {//是主播
//                [self.tabBar hideBadgeOnItemIndex:2];
//            }else{
//                [self.tabBar hideBadgeOnItemIndex:3];
//            }
            [self.tabBar hideBadgeOnItemIndex:2];
        }
    }];
    
    //直播tabbar
    if (![[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {//是主播
        [UIView animateWithDuration:2 animations:^{
            
        } completion:^(BOOL finished) {
            if (![[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]){
//                [self setupLaunchMask];
            }
        }];
    }
    
    
//    //是否是新用户
//    BOOL isNewUser = [UserDefaults boolForKey:NewUser];
//
//    //用户界面 且 是新用户
//    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"0"] && isNewUser) {
//
//        /**
//         添加引导功能
//         */
//        [self layOutFunctionalGuidance];
//
//    }
}

/**
 功能引导
 */
- (void)layOutFunctionalGuidance
{
    //功能引导图
    self.guidanceView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    self.guidanceView.userInteractionEnabled = YES;
    
    //查找沙盒图片
    NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
    
    NSString *filePath = [resourcePath stringByAppendingPathComponent:@"pop_pic_qiuban"];
    
    UIImage *fileImage = nil;
    
    //8.0 和 7.0 系统版本要使用这个方法加载图片不同
    if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
        fileImage = [UIImage imageWithContentsOfFile:filePath];
    }else{
        fileImage = [UIImage imageWithContentsOfFile:[filePath stringByAppendingString:@"@2x.png"]];
    }
    
    self.guidanceView.image = fileImage;
    
    [self.view addSubview:self.guidanceView ];
    
    //添加点击手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapFunctionalGuidance:)];
    
    tapGesture.numberOfTapsRequired = 1;
    
    [self.guidanceView  addGestureRecognizer:tapGesture];
    
}

//点击功能引导
- (void)tapFunctionalGuidance:(UITapGestureRecognizer *)sender
{
    NSLog(@"点击了功能引导！");
    
    [self.guidanceView removeFromSuperview];
}

//设置tabbar
- (XLNavgationViewController *)creatViewControllerWithTitle:(NSString *)title controllerClass:(Class)controllerClass normalImageName:(NSString *)normalImageName selectImageName:(NSString *)selectImageName {
    
    UIImage *imageNormal = [[UIImage imageNamed:normalImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage *imageSelected = [[UIImage imageNamed:selectImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIViewController *controller = [[controllerClass alloc] init];
    XLNavgationViewController *navController = [[XLNavgationViewController alloc] initWithRootViewController:controller];
    if ([title isEqualToString:@"直播"]) {
        navController.tabBarItem.imageInsets = UIEdgeInsetsMake(-6, 0, -8, 0);
    }
    navController.tabBarItem = [[UITabBarItem alloc] initWithTitle:title image:imageNormal selectedImage:imageSelected];
    navController.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -4);
    [navController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : kBlackColor,NSFontAttributeName : [UIFont systemFontOfSize:10]} forState:UIControlStateSelected];
    [navController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : kDarkGrayColor,NSFontAttributeName : [UIFont systemFontOfSize:10]} forState:UIControlStateNormal];
    return navController;
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    //    if (tabBarController.selectedIndex == 0) {
    //        tabBarController.tabBar.translucent = YES;
    //        [tabBarController.tabBar setBackgroundImage:[UIImage imageWithSolidColor:RGBA(255, 255, 255, 0) size:CGSizeMake(ScreenWidth, 49)]];
    //        [tabBarController.tabBar setShadowImage:[UIImage imageWithSolidColor:RGBA(255, 255, 255, 0.5) size:CGSizeMake(ScreenWidth, 1.0 / [UIScreen mainScreen].scale)]];
    //    } else {
    //        tabBarController.tabBar.translucent = NO;
    //        [tabBarController.tabBar setBackgroundImage:[UIImage imageWithSolidColor:RGBA(26, 25, 38, 1) size:CGSizeMake(ScreenWidth, 49)]];
    //        [tabBarController.tabBar setShadowImage:[UIImage imageWithSolidColor:RGBA(46, 45, 57, 0.5) size:CGSizeMake(ScreenWidth, 1.0 / [UIScreen mainScreen].scale)]];
    //    }
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    if ([tabBarController.selectedViewController isEqual:[tabBarController.viewControllers firstObject]] && [viewController isEqual:tabBarController.selectedViewController]) { //推荐
        [[NSNotificationCenter defaultCenter] postNotificationName:@"repeatSelectRecommand" object:nil];
    }
    if ([tabBarController.selectedViewController isEqual:[tabBarController.viewControllers objectAtIndex:1]] && [viewController isEqual:tabBarController.selectedViewController]) { //推荐
        [[NSNotificationCenter defaultCenter] postNotificationName:@"repeatSelectMessage" object:nil];
    }
    return YES;
}

- (void)playSound {
    SystemSoundID soundID;
    NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"noticeAudio" ofType:@"wav"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef) [NSURL fileURLWithPath:soundFile], &soundID);
    AudioServicesPlaySystemSound(soundID);
}

- (void)dealloc {
    [self.disposable dispose];
    NSLog(@"dealloc tabbarcontroller");
}

- (void)showBadgeOnItemIndex:(int)index {
    [self.tabBar showBadgeOnItemIndex:index];
}

- (void)hideBadgeOnItemIndex:(int)index {
    [self.tabBar hideBadgeOnItemIndex:index];
}

#pragma mark -
- (BOOL)shouldAutorotate{
    return [self.selectedViewController shouldAutorotate];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return [self.selectedViewController supportedInterfaceOrientations];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return [self.selectedViewController preferredInterfaceOrientationForPresentation];
}
@end
